package com.genersoft.iot.vmp.gb28181.utils;

import gov.nist.javax.sip.address.AddressImpl;
import gov.nist.javax.sip.address.SipUri;
import org.springframework.util.StringUtils;

import javax.sip.header.FromHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;

/**
 * @author panlinlin
 * @version 1.0.0
 * @description JAIN SIP的工具类
 * @createTime 2021年09月27日 15:12:00
 */
public class SipUtils {

    public static String getUserIdFromFromHeader(Request request) {
        FromHeader fromHeader = (FromHeader)request.getHeader(FromHeader.NAME);
        return getUserIdFromFromHeader(fromHeader);
    }

    public static String getUserIdFromFromHeader(FromHeader fromHeader) {
        AddressImpl address = (AddressImpl)fromHeader.getAddress();
        SipUri uri = (SipUri) address.getURI();
        return uri.getUser();
    }

    public static String getIpFromViaHeader(Request request){
        ViaHeader viaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
        return getIpFromViaHeader(viaHeader);
    }

    public static String getIpFromViaHeader(ViaHeader viaHeader){
        String received = viaHeader.getReceived();
        // 解析本地地址替代
        if (StringUtils.isEmpty(received)) {
            received = viaHeader.getHost();
        }
        return received;
    }

    public static int getPortFromViaHeader(Request request){
        ViaHeader viaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
        return getPortFromViaHeader(viaHeader);
    }

    public static int getPortFromViaHeader(ViaHeader viaHeader){
        int rPort = viaHeader.getRPort();
        // 解析本地地址替代
        if (rPort == -1) {
            rPort = viaHeader.getPort();
        }
        return rPort;
    }

    public static String getHostAddress(Request request){
        String received = getIpFromViaHeader(request);
        int rPort = getPortFromViaHeader(request);
        return received.concat(":").concat(String.valueOf(rPort));
    }
}
